package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    /**
     * 查询自媒体文章列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //1.检查参数
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.分页参数检查
        dto.checkParam();
        //3.分页条件查询
        Page page = new Page(dto.getPage(),dto.getSize());
        //3.1 状态精确查询
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (dto.getStatus() != null){
            lambdaQueryWrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        //3.2 频道精确查询
        if (dto.getChannelId() != null){
            lambdaQueryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
        //3.3 时间范围查询
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null){
            lambdaQueryWrapper.between(WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }
        //3.4 关键字模糊查询
        if (StringUtils.isNotBlank(dto.getKeyword())){
            lambdaQueryWrapper.like(WmNews::getTitle,dto.getKeyword());
        }
        //3.5 查询当前登录用户的文章
        lambdaQueryWrapper.eq(WmNews::getUserId, WmThreadLocalUtil.getUser().getId());
        //3.6 按照发布时间倒序查询
        lambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);

        page = page (page,lambdaQueryWrapper);
        //4 返回结果
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }


    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;
    /**
     * 提交，修改，保存草稿
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) {
        //1.检查文章
        if (dto == null && StringUtils.isBlank(dto.getContent())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.保存或者修改文章
        WmNews wmNews = saveOrUpdateNews(dto);


        //3.如果状态为0 则保存为草稿
        if (dto.getStatus().equals(WmNews.Status.NORMAL.getCode())){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        //4.从内容中获取图片
        List<String> materials = ectractUrlInfo(dto.getContent());

        //5.保存文章内容图片与素材的关系
        saveRelativeInfoForContent(materials,wmNews.getId());

        //6.保存文章封面图片与素材的关系
        saveRelativeInfoForCover(dto,wmNews,materials);


        //7.文章发布之后需要提交审核
        wmNewsAutoScanService.autoScanWmNews(wmNews.getId());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    //6.保存文章封面图片与素材的关系
    /**
     * 1.如果文章封面选择自动，则自动匹配封面
     *      匹配规则：
     *     如果内容图片大于等于3  则是多图，截图3张图片作为封面
     *    如果内容图片大于等于1&&小于3  则是单图，截图1张图片作为封面
     *   如果内容没有图片，则是无图
     *
     *   2.保存封面图片与素材的关系
     * @param dto
     * @param wmNews
     * @param materials
     */
    private void saveRelativeInfoForCover(WmNewsDto dto, WmNews wmNews, List<String> materials) {
        //6.1 获取封面图片
        List<String> images = dto.getImages();

        //6.2 如果文章封面选择自动 则自动匹配封面
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            int size = materials.size();
            if (size >= 3){
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);  //WM_NEWS_MANY_IMAGE = 3张
                images = materials.stream().limit(3).collect(Collectors.toList());
            }else if (size >= 1 && size < 3){
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE); //WM_NEWS_SINGLE_IMAGE = 1张
                images = materials.stream().limit(1).collect(Collectors.toList());
            }else {
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);  //WM_NEWS_NONE_IMAGE 表示无图
            }
            //如果封面的图片不为null 以逗号分割放在wmNews对象中
            if (images != null && images.size() > 0){
                wmNews.setImages(StringUtils.join(images,","));
            }

            //更新保存文章
            updateById(wmNews);
        }
        //保存封面图片与素材的关系
        if (images != null && images.size() > 0 ){
            saveRelativeInfo(images,wmNews.getId(),WemediaConstants.WM_COVER_REFERENCE
            );
        }

    }

    //5.保存文章内容图片与素材的关系
    private void saveRelativeInfoForContent(List<String> materials, Integer newsId) {
        saveRelativeInfo(materials,newsId,WemediaConstants.WM_CONTENT_REFERENCE);
    }


    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    /**
     * 接着上面的 第 5 步
     * 保存文章图片与素材的关系到数据库中
     * @param materials
     * @param newsId
     * @param type
     */
    private void saveRelativeInfo(List<String> materials, Integer newsId, Short type) {
        if (materials != null && materials.size() > 0){
            /*//5.1根据图片的url 查询对应的id
            materials = materials.stream().distinct().collect(Collectors.toList());
            LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.in(WmMaterial::getUrl,materials);
            List<WmMaterial> dbMaterials = wmMaterialMapper.selectList(lambdaQueryWrapper);

            if (dbMaterials == null || dbMaterials.size() == 0 || dbMaterials.size() != materials.size()){
                //素材没找到 或没有找够 抛出异常 并提示用户 引用失效
                throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);
            }*/
            //根据图片url查询对应的id
            materials = materials.stream().distinct().collect(Collectors.toList());
            List<WmMaterial> dbMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, materials));
            if(dbMaterials == null || dbMaterials.size() == 0 || dbMaterials.size() != materials.size()){
                //素材没找到，或没找够
                //抛出异常，并提示用户，素材引用失效
                throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);
            }

            //5.2 取出id
            List<Integer> listId= dbMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());

            wmNewsMaterialMapper.saveRelations(listId,newsId,type);
        }
    }


    //4 从内容中提取图片
    private List<String> ectractUrlInfo(String content) {
        ArrayList<String> materials = new ArrayList<>();

        //4.1 将JSON数组对象转为java对象
        List<Map> maps = JSON.parseArray(content, Map.class);
        //4.2 遍历获取里面的图片
        for (Map map : maps) {
            if (map.get("type").equals("image")){
                materials.add((String) map.get("value"));
            }
        }
        return materials;
    }


    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    //2.保存文章或者修改文章
    private WmNews saveOrUpdateNews(WmNewsDto dto) {
        WmNews wmNews = new WmNews();
        //2.1对象拷贝
        BeanUtils.copyProperties(dto,wmNews);
        //2.2 图片处理
        if (dto.getImages() != null && dto.getImages().size() > 0){
            //2.2.1 从集合转换为字符串  [1234.jpg,45678.jpg]
            String imagesStr = StringUtils.join(dto.getImages(), ",");
            //2.2.2 把它存在WmNews 中
            wmNews.setImages(imagesStr);
        }
        //2.3如果图片在上传的时候 如果选择自动 则值为-1 暂时修改为null 后面还需要修改
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            wmNews.setType(null);
        }

        //2.4 补充其他数据
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setEnable((short) 1);
        wmNews.setSubmitedTime(new Date());


        //2.5提交或者修改  提交时是没有id的 如果当它等于null的时候提交时候我们需要保存它
        if (dto.getId() == null){
            //保存
            save(wmNews);
        }else {
            //修改  在修改之前时候我们需要将文章图和素材的关系删除'
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,dto.getId()));
            //在修改
            updateById(wmNews);
        }
        return wmNews;
    }
}
